<template>
  <p-card>
    <p-page-header
            style="border: 1px solid rgb(235, 237, 240)"
            title="生成巡检待检任务"
    >
      <template slot="extra">
        <p-popconfirm
                title="确定要提交吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="submitData"
                @cancel="cancel"
        >
          <p-button type="primary">提交</p-button>
        </p-popconfirm>

        <p-button @click="backToIndex">取消</p-button>
      </template>
    </p-page-header>

    <h4 class="title">基础信息</h4>

    <p-form-model
      ref="baseInfoData"
      :model="baseInfoData"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <p-row :gutter="24">
        <p-col :span="8">
          <p-form-model-item ref="inspectBillno" label="送检单号" prop="inspectBillno">
            <p-input
                    readOnly
              v-model="baseInfoData.inspectBillno"
              @blur="
          () => {
            $refs.inspectBillno.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="processOne" label="一级工序" prop="processOne">
            <p-input
                    readOnly
              v-model="baseInfoData.processOne"
              @blur="
          () => {
            $refs.processOne.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="processTwo" label="二级工序" prop="processTwo">
            <p-input
                    readOnly
              v-model="baseInfoData.processTwo"
              @blur="
          () => {
            $refs.processTwo.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="sendTime" label="送检时间" prop="sendTime">
            <p-input
                    readOnly
              v-model="baseInfoData.sendTime"
              @blur="
          () => {
            $refs.sendTime.onFieldBlur();
          }
        "
            />
          </p-form-model-item>
        </p-col>
        <p-col :span="8">
          <p-form-model-item ref="mid" label="品号" prop="mid">
            <p-select
                    allowClear
                    show-search
                    v-model="baseInfoData.mcode"
                    placeholder="please select your zone"
                    @change="productChange"
            >
              <p-select-option
                      v-for="(item,index) in productList"
                      :key="index"
                      :value="item"
              >{{item}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>
        <p-col :span="8" v-if="baseInfoData.mcode&&baseInfoData.mcode!=''">
          <p-form-model-item ref="processBillno" label="工单" prop="processBillno">
            <p-select
                    mode="multiple"
                    showSearch
                    v-model="processBillnoValues"
                    @change="processBillnoSelectChange"
            >
              <p-select-option
                      v-for="(item,index) in processBillnoList"
                      :key="index"
                      :value="item"
              >{{item}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>
        <p-col :span="8" v-if="baseInfoData.mcode&&baseInfoData.mcode!=''">
          <p-form-model-item ref="lineid" label="线别" prop="lineid">
            <p-select
                    mode="multiple"
                    showSearch
                    v-model="lineidValues"
                    @change="lineidSelectChange"
            >
              <p-select-option
                      v-for="(item,index) in lineList"
                      :key="index"
                      :value="item.linename"
              >{{item.linename}}</p-select-option>
            </p-select>
          </p-form-model-item>
        </p-col>

      </p-row>
    </p-form-model>
    <h4 class="title">送检产品明细</h4>
    <!--resultState-->
    <p-alert v-if="tipsState==1"  message="无可选的送检产品明细列表" type="warning" show-icon />
    <p-alert v-if="tipsState==2"  message="请勾选送检产品明细" type="info" show-icon />
    <div v-if="tipsState==3" class="ant-alert ant-alert-success"  style="margin-bottom: 16px;">
      <p-icon type="check-circle" style="background-color: #33cc66;border-radius: 60px;color:white;font-size:20px" />
      <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
      <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
      <a style="margin-left: 24px" @click="clearSelectRow">清空</a>
    </div>

    <p-table
      :columns="inspectionProductsColumns"
      :data-source="inspectionProductsData"
      class="components-table-demo-nested"
      bordered
      style="margin-top:10px;"
      :rowSelection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps:getCheckboxProps
      }"
      :customRow="setRow"
    ></p-table>


  </p-card>
</template>

<script>
// import { JeecgListMixin } from "@/mixins/JeecgListMixin";
import { api } from "@/api/manage";
import JSuperQuery from "@/components/jeecg/JSuperQuery.vue";
import { filterObj } from "@/utils/util";
import Vue from "vue";
import  dayjs   from 'dayjs';
import {getAction,postAction} from "../../../../api/manage";

export default {
  name: "MesQcTourinspectGenerate",
  // mixins: [JeecgListMixin],
  props:['mqVisible','mqLoad','mqData'],
  data() {
    return {
      labelCol: { span: 7 },
      wrapperCol: { span: 16 },
      selectedRowKeys: [],
      selectedRows: [],

      productList:[],
      processBillnoList:[],
      processBillnoValues:[],
      lineList:[],
      lineidValues:[],



      firstProductionnoList:[],
      firstLineList:[],
      tipsState:1,

      rules: {
        inspectBillno: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        processOne: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        processTwo: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        sendTime: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        sendDimensionProcode: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        sendDimensionWork: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
        sendDimensionLine: [
          {
            required: true,
            message: "Please input Activity name",
            trigger: "blur",
          },
        ],
      },

      modal2Visible: false,
      baseInfoData: {
        //基础信息
        inspectBillno: "001", //送检单号
        processOne: "", //一级工序
        processTwo: "", //二级工序
        sendTime: dayjs().format('YYYY-MM-DD HH:mm:ss') , //送检时间
        mcode: '', //品号
        processBillno: '', //工单
        linename: '', //线别
      },

      inspectionProductsColumns: [
        {
          title: "序号",
          dataIndex: "",
          key: "rowIndex",
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          },
        },
        { title: "二级工序", dataIndex: "processTwo", key: "processTwo" },
        { title: "线体", dataIndex: "linename", key: "linename" },
        {
          title: "生产工单",
          dataIndex: "productionBillno",
          key: "productionBillno",
        },
        { title: "工序工单", dataIndex: "processBillno", key: "processBillno" },
        { title: "产品编码", dataIndex: "mcode", key: "mcode" },
        { title: "产品名称", dataIndex: "mname", key: "mname" },
        { title: "工单数量", dataIndex: "billnoQty", key: "billnoQty" },
      ],


      firstInspectionProductsData:[],
      inspectionProductsData: [

      ],

      productArray:[],
      productAllInfo:[],

    };
  },
  computed: {
    // checkBox属性设置
    getCheckboxProps(record) {
      return (record) => ({
        props: {
          // defaultChecked: record.key === this.modal2InspectionData[0].key,
        },
      });
    },
  },




  created() {
    this.mqListener();
  },

  methods: {
    mqListener(){
      console.log(this.mqVisible)
      console.log(this.mqLoad)
      console.log(this.mqData)
      this.initData(this.mqData);
    },
    backToIndex(){
      let mqData = this.mqData;
      this.$emit('update:mqVisible', 1);
      this.$emit('update:mqLoad', false);
      mqData.id = 0;
      mqData.isPallet = "";
      mqData.inspectStatus = "";
      this.$emit('update:mqData', mqData);
    },
    setRow(record) {
      return {
        on: {
          click: () => {
            let rowKeys = this.selectedRowKeys;
            if (rowKeys.length > 0 && rowKeys.includes(record.key)) {
              rowKeys.splice(rowKeys.indexOf(record.key), 1);
            } else {
              rowKeys.push(record.key);
            }
            this.selectedRowKeys = rowKeys;
            console.log(this.selectedRowKeys);
          },
        },
      };
    },
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);

      this.selectedRowKeys = selectedRowKeys;

      this.setTipsState();
    },

    //初始化数据
    initData(query){

      if(!query.id){
        this.$message.warning("请通过巡检任务清单选择单号进入！");

      }else{
        let id = query.id;

        getAction('/mes-quality/mesQcTourInspectTask/selectById',{id:id}).then(res=>{
          if (res.success) {
            if(res.code!=0){
              this.$message.warning(res.msg)
            }
            let data = res.data;

            this.baseInfoData = data;
            this.baseInfoData.sendTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

            this.initSendProjectDetails();


            /*this.queryParamList();*/
          } else {
            this.$message.warning("后台获取单据信息报错");
          }
        })

      }
    },

    queryParamList(){
      let data= {
        endDate:dayjs().format('YYYY-MM-DD')+" 23:59:59",
        processCoding:'',
        processTwocode:'',
        processVersion:'',
        startDate:dayjs().format('YYYY-MM-DD')+" 00:00:00",
      }
      console.log(data)
      /*getAction('/mes-manufacture/mfProcess/getQualityFilter',)*/
    },

    //产品下拉change事件
    productChange(value){
      console.log(value)
      //清空已选择的工单和线别
      this.processBillnoValues=[];
      this.lineidValues = [];
      //根据value请求该产品对应的工单和线别list

      if(!this.baseInfoData.mcode||this.baseInfoData.mcode==''){
        this.processBillnoList = [];
        this.lineList = [];
        this.inspectionProductsData = this.firstInspectionProductsData;

        this.clearSelectRow();
      }else{
        this.initProcessBillnoList();
        this.initLineList();
        this.resetCheckProjectList();
      }

    },
    //工单下拉change事件
    processBillnoSelectChange(value){
      console.log(value)
      this.resetCheckProjectList();
    },
    //线别下拉change事件
    lineidSelectChange(value){
      console.log(value)
      this.resetCheckProjectList();
    },

    //清空已勾选的检验项目明细
    clearSelectRow(){
      this.selectedRowKeys= [];
      this.selectedRows= [];
      this.setTipsState();
    },


    //重置检验项目明细
    resetCheckProjectList(){
      this.clearSelectRow();
      let mcode = this.baseInfoData.mcode;
      let processBillnoValues = this.processBillnoValues;
      let lineidValues = this.lineidValues;

      let firstData = this.firstInspectionProductsData;
      let dataByMid = [];
      let usedKey = new Set();
      let resultData = [];

      firstData.forEach(item=>{
        if(mcode==item.mcode){
          dataByMid.push(item);
        }
      })

      console.log(dataByMid)

      if(processBillnoValues.length>0&&lineidValues.length>0){
        dataByMid.forEach(item=>{
          item.productionnoFlag  = false;
          item.linenameFlag = false;
          processBillnoValues.forEach(j=>{
            if(item.productionno==j){
              item.productionnoFlag = true;
            }
          })
          lineidValues.forEach(o=>{
            if(item.linename == o){
              item.linenameFlag = true;
            }

          })

          if(item.productionnoFlag==true&&item.linenameFlag==true){
            resultData.push(item)
          }
        })

        this.inspectionProductsData = resultData;

      }else if(processBillnoValues.length>0||lineidValues.length>0){
        /*let dataMap1 = this.listToMap(dataByMid,'productionno');*/
        processBillnoValues.forEach(item=>{
          /*if(dataMap1[item]){
            usedKey.add(dataMap1[item].key);
          }*/
          dataByMid.forEach(j=>{
            if(j.productionno==item){
              usedKey.add(j.key);
            }
          })
        })
        /*let dataMap2 = this.listToMap(dataByMid,'linename');*/
        lineidValues.forEach(item=>{
          /*if(dataMap2[item]){
            usedKey.add(dataMap2[item].key);
          }*/
          dataByMid.forEach(j=>{
            if(j.linename==item){
              usedKey.add(j.key);
            }
          })
        })

        let dataMap3 = this.listToMap(dataByMid,'key');
        for(let key of usedKey){
          if(dataMap3[key]){
            resultData.push(dataMap3[key]);
          }
        }

        this.inspectionProductsData = resultData;
      }else{
        this.inspectionProductsData =dataByMid;
      }


      this.setTipsState();

    },


    //封装listToMap
    listToMap(list,name){
      let map = {};
      for(let i in list){
        map[list[i][name]] = list[i];
      }
      return map;
    },




    //初始化线体列表
    initLineList(){
      let productArray = this.productList ;
      let productAllInfo = this.productAllInfo;
      let index = productArray.indexOf(this.baseInfoData.mcode);
      if(index!=-1){
        this.lineList  = productAllInfo[index].lineList;
      }else{
        this.lineList  = [];
      }

    },

    //初始化工序工单列表
    initProcessBillnoList(){
      let productArray = this.productList ;
      let productAllInfo = this.productAllInfo;
      let index = productArray.indexOf(this.baseInfoData.mcode);
      if(index != -1){
        this.processBillnoList  = productAllInfo[index].pbnList;
      }else{
        this.processBillnoList = [];
      }

    },

    //提交数据
    submitData(){
      let data = this.baseInfoData;

      let flag = true;

      let mcode = data.mcode;
      if(mcode){
        let productMap = this.listToMap(this.productList,'mcode');
        if(productMap[mcode]){
          data.mname = productMap[mcode].mname;
        }
      }else{
        flag = false;
        this.$message.warning('请选择一个品号!');
      }


      if(flag){
        data.mesQcTourinspProductDetailList = this.getCheckProjectDetailsBySelectRows();


        postAction('/mes-quality/mesQcTourInspectTask/saveTourInspectTask',data).then(res=>{
          if(res.success){
            this.$message.success("提交成功!");
            this.backToIndex();
          }else{
            this.$message.error(res.msg);
          }
        })
      }




    },

    listToSetThenString(list,name){
      let result = '';
      let strSet = new Set();

      list.forEach(item=>{
        strSet.add(item[name]);
      })
      for(let str of strSet){
        result+=str+',';
      }

      if(list.length>0){
       result= result.substring(0,result.length-1)
      }

      return result;

    },

    //根据selectRows获取具体勾选的送检产品list
    getCheckProjectDetailsBySelectRows(){
      let selectedRowKeys  = this.selectedRowKeys ;
      if(selectedRowKeys.length>0){
        let resultData = [];
        let dataMap  = this.listToMap(this.inspectionProductsData,'key');
        selectedRowKeys.forEach(item=>{
          resultData.push(dataMap[item]);
        })

        return resultData;
      }
      return [];
    },

    listToString(list){
      let result = '';
      list.forEach(item=>{
        result+=item;
        result+=',';
      })
      if(list.length>0){
        result = result.substring(0,result.length-1);
      }

      return result;
    },

    setTipsState(){
      if(this.inspectionProductsData.length==0){
        this.tipsState=1;
      }else{
        if(this.selectedRowKeys.length==0){
          this.tipsState=2;
        }else{
          this.tipsState=3;
        }
      }
    },

   //初始化送检产品明细
    initSendProjectDetails(){

      let date = dayjs().format('YYYY-MM-DD HH:mm:ss');
      let processTwoCode = this.baseInfoData.processTwoCode;

      getAction('/mes-manufacture/mfProcess/getWorkedOrder?date='+date+'&processTwocode='+processTwoCode).then(res=>{
          if(res.success){
            let data = [];
            if(res.data){
              data = res.data;
            }
            let key = 1;

            let productArray = [];
            let productAllInfo = [];
            data.forEach(item=>{
              item.key  = key;
              key = key + 1;


              item.processTwo = item.processTwoname;
              item.productionBillno = item.productionno;
              item.processBillno = item.processbillno;
              item.billnoQty = item.planQty;
              item.mcode = item.productcode;
              item.mname = item.productname;
              item.sprc = item.productsprc;



              if(productArray.indexOf(item.mcode)==-1){
                productArray.push(item.mcode);

                let info = {mcode:item.mcode,pbnList:[],lineList:[]};
                info.pbnSet = new Set();
                info.lineSet = new Set();
                productAllInfo.push(info)
              }

              let  pIndex = productArray.indexOf(item.mcode);

              if(!productAllInfo[pIndex].pbnSet.has(item.pMesQcTourInspectTaskListMenuroductionBillno)){

                productAllInfo[pIndex].pbnSet.add(item.productionBillno);
                productAllInfo[pIndex].pbnList.push(
                        item.productionBillno
                )
              }

              if(!productAllInfo[pIndex].lineSet.has(item.lineno)){
                productAllInfo[pIndex].lineSet.add(item.lineno);
                productAllInfo[pIndex].lineList.push(
                        {lineno:item.lineno,linename:item.linename}
                )
              }



            })

            this.firstInspectionProductsData = data;
            this.inspectionProductsData = data;

            this.productList = productArray;
            this.productAllInfo = productAllInfo;

            this.setTipsState();
          }else{
            this.$message.warning(res.msg)
          }
      })


    }

  },
};
</script>
<style scoped>
@import "~@assets/less/common.less";
.title {
  padding: 8px 12px;
  background: #fafafa;
}
.title:not(:first-child) {
  margin-top: 25px;
}
.poros-form {
  margin-top: 15px;
}
/deep/ .poros-table-body {
  overflow-x: auto !important;
}
/deep/ .poros-table thead th{
  height:44px;
}
/deep/ .poros-col{
  min-height: 54px;
}
</style>
